package com.bonc.controller;


import com.bonc.util.exception.BusinessException;
import com.bonc.util.request.ServletUtils;
import com.bonc.util.response.CommResponseEnum;
import com.bonc.web.user.SysLoginService;
import com.google.code.kaptcha.Constants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpSession;

/**
 * @Description: 登录控制类
 * @Author: ChenZhiXiang
 * @CreateDate: 2018/11/21 0021 10:27
 * @Version: 1.0
 */
@Controller
@RequestMapping("/login")
@Api("登录")
public class LoginController {

    private static Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Value("${CryptographicKey}")
    private String KEY;

    @Value("${CryptographicIV}")
    private String IV;

    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 登录接口
     * @param userName  用户名
     * @param password  密码
     * @param code      验证码
     * @return
     * @throws Exception
     */
    @ApiOperation(httpMethod = "POST", value = "登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query")
    })
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object userLogin(String userName, String password, String code) throws Exception
    {
        HttpSession session = ServletUtils.getRequest().getSession();
        // 前端传过来的密码是加密的，需要解密
        /*String desEncryptPassword = AesUtilWeb.aesEncrypt(password);*/
        // 拿到存储到session中的验证码
        String sessionCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        logger.info("前端传入验证码："+code+"，session中验证码"+sessionCode);
        // 判断session中的验证码是否为空
        if (null == sessionCode || sessionCode.equals(""))
        {
            throw new BusinessException(CommResponseEnum.USER2);
        }
        // 验证码不区分大小写
        if (!code.toUpperCase().equals(sessionCode.toUpperCase()))
        {
            throw new BusinessException(CommResponseEnum.USER2);
        }
        // 验证后清除session中的验证码
        session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        // 调用登录方法
        return sysLoginService.login(userName,password);
    }
    /**
      * @Description: 退出跳转
      * @Author: ChenZhiXiang
      * @CreateDate: 2018/11/21 0021 14:38
      * @Version: 1.0
    * */
   /* @RequestMapping(value = "/logout")
    public void logout(HttpSession session, HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        //退出操作记录
        LogRecords logRecords = new LogRecords();
        LoginUser user = (LoginUser) request.getSession().getAttribute("user");
        logRecords.setUsername(user.getUsername());
        logRecords.setOperation(OperationEnum.getDesc("logout"));
        logRecords.setOperationTime(new Date());
        logRecords.setIP(IPUtil.getIpAddr(request));
        logRecordsService.insertLogRecords(logRecords);
        //清除session
        session.removeAttribute("user");
        request.getSession().invalidate();
        //返回请求头
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("pragma", "no-cache");

        //重定向到登录页面
        response.sendRedirect(request.getContextPath() + "/login.html");
        return;
        *//* return "redirect:/login"; *//*
    }*/
}
